package com.baosight.risk.web.zbaa;

import com.baosight.risk.api.rire.RiwaRiskWaringService;
import com.baosight.risk.api.xtzy.IXtzyIntegralService;
import com.baosight.risk.api.zbaa.IZbaaTargetGroupOrderService;
import com.baosight.risk.api.zbaa.IZbaaTargetGroupService;
import com.baosight.risk.api.zbaa.IZbaaTargetService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.BusinessType;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetGroup;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetGroupOrder;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetGroupOrderVo;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetGroupVo;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetValueVO;
import com.baosight.risk.web.page.PageDomain;
import com.baosight.risk.web.page.TableSupport;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/zbaa/target/group")
@Api(value = "指标看板", description = "指标看板", produces = MediaType.APPLICATION_JSON)
public class ZbaaTargetGroupController extends BaseController {

    @Autowired
    private IZbaaTargetGroupService targetGroupService;

    @Autowired
    private IZbaaTargetGroupOrderService targetGroupOrderService;

    @Autowired
    private IZbaaTargetService targetService;

    @Autowired
    private RiwaRiskWaringService waringService;

    @Autowired
    private IXtzyIntegralService integralService;

    /**
     * 根据用户查找自身的指标列表
     *
     * @return
     */
    @GetMapping("selectTargetListByUser")
    @ApiOperation("根据用户查找自身的指标列表")
    public AjaxResult selectTargetListByUser(HttpServletRequest request) {

        // 获取当前用户重点风险指标（内部指标）
        List<ZbaaTarget> warningList = waringService.getTargetByImport("", getUser().getExt1(), "");

        // 获取全部外部指标
        List<ZbaaTarget> outTargetList = targetService.getTargetListByRiskSource("W");
        outTargetList.addAll(warningList);

        // 模糊查询处理
        List<ZbaaTarget> resultList = new ArrayList();
        // 根据指标名称对查询结果过滤
        String targetName = request.getParameter("targetName");
        String manageCompName = request.getParameter("manageCompName");
        Pattern pattern = Pattern.compile(targetName);

        for (int i = 0; i < outTargetList.size(); i++) {
            Matcher matcher = pattern.matcher(outTargetList.get(i).getTargetName());
            if(StringUtils.isNotBlank(manageCompName)){//传
                Pattern pattern1 = Pattern.compile(manageCompName);
                if(StringUtils.isNotEmpty(outTargetList.get(i).getManageCompName())){
                    Matcher matcher1 = pattern1.matcher(outTargetList.get(i).getManageCompName());
                    if (matcher.find()&&matcher1.find()) {
                        resultList.add(outTargetList.get(i));
                    }
                }
            }else{//不传
                if (matcher.find()) {
                    resultList.add(outTargetList.get(i));
                }
            }
        }

        // 手动分页处理
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageIndex = pageDomain.getPageIndex();
        Integer pageSize = pageDomain.getPageSize();

        Integer start = pageSize * (pageIndex - 1);
        Integer end = pageSize * pageIndex - 1;
        end = end <= resultList.size() - 1 ? end : resultList.size() - 1;

        List<ZbaaTarget> pageList = new ArrayList();
        for (int i = start; i <= end; i++) {
            pageList.add(resultList.get(i));
        }

        // 拼接返还结果
        AjaxResult result = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", new PageInfo(resultList).getTotal());
        map.put("data", pageList);
        result.put("msg", "查询结果");
        result.put("code", 200);
        result.put("data", map);
        return result;
    }

    /**
     * 根据用户查找自身的指标看板分组
     *
     * @return
     */
    @GetMapping("selectGroupByUser")
    @ApiOperation("根据用户查找自身的指标看板分组")
    public AjaxResult selectGroupByUser(HttpServletRequest request) {
        List<ZbaaTargetGroup> zbaaTargetGroupList = targetGroupService.selectGroupByUserId(getUser().getUserCode());
        return success(zbaaTargetGroupList);
    }

    /**
     * 保存当前用户的看板分组
     *
     * @param targetGroup
     * @return
     */
    @PostMapping("saveTargetGroup")
    @Log(title = "保存看板分组", businessType = BusinessType.INSERT)
    @ApiOperation("保存看板分组")
    public AjaxResult saveTargetGroup(@RequestBody ZbaaTargetGroup targetGroup) {
        if (!integralService.checkGroupLimit()) {
            return error("当前用户等级已达到创建看板分组上限");
        }

        log.info("保存指标看板参数：" + targetGroup.toString());
        //初始化基本参数
        targetGroup = (ZbaaTargetGroup) BeanUtils.initBean(targetGroup);
        targetGroup.setUserCode(getUser().getUserCode());
        targetGroup.setUserDesc(getUser().getUserDesc());
        return toAjax(targetGroupService.insert(targetGroup));
    }

    /**
     * 删除用户选择的看板分组
     *
     * @param id
     * @return
     */
    @GetMapping("deleteTargetGroup")
    @ApiOperation("删除用户选择的看板分组")
    public AjaxResult deleteTargetGroup(@RequestParam("id") String id) {
        return toAjax(targetGroupService.deleteById(id));
    }

    /**
     * 修改看板分组
     *
     * @param targetGroup
     * @return
     */
    @PostMapping("updateTargetGroup")
    @Log(title = "修改看板分组")
    @ApiOperation("修改看板分组")
    public AjaxResult updateTargetGroup(@RequestBody ZbaaTargetGroup targetGroup) {
        Integer result = targetGroupService.update(targetGroup);
        return toAjax(result);
    }

    /**
     * 根据看板分组Id查找自全部看板中指标
     *
     * @return
     */
    @GetMapping("selectGroupOrderByGroupId")
    @ApiOperation("根据分组Id查找自全部订阅指标")
    public AjaxResult selectGroupOrderByGroupId(@RequestParam("id") String groupId) {
        List<ZbaaTargetGroupOrderVo> resultList = new ArrayList<>();

        List<ZbaaTargetGroupOrder> zbaaTargetGroupList = targetGroupOrderService.selectGroupOrderByGroupId(groupId);

        for (ZbaaTargetGroupOrder targetGroupOrder : zbaaTargetGroupList) {

            ZbaaTargetGroupOrderVo result = new ZbaaTargetGroupOrderVo();

            //拼接当前订阅指标数据
            String targetNo = targetGroupOrder.getTargetNo();
            String compCode = targetGroupOrder.getCompCode();
            String period = targetGroupOrder.getTargetPeriodName();
            String endTime = DateUtils.format(new Date(), "yyyy-MM-dd");
            String interval = "10";
            String startTime = DateUtils.caculateTime(endTime, period, interval);
            if (period.equals("季")) {
                // 季度数据单独处理过滤范围
                int year = Integer.parseInt(endTime.substring(0, 4)) + 1;
                endTime = year + "-01-01";
            }

            List<String> companyCodeList = new ArrayList<>();
            companyCodeList.add(compCode);
            List<ZbaaTargetValueVO> targetValueVO = targetService.getValue(targetNo, companyCodeList, startTime, endTime, period);

            // 获取当前指标数据更新时间
            ZbaaTargetValue zbaaTargetValue = targetService.getLastZbaaTargetInfo(targetNo, compCode);
            // 获取当前指标的定义，对应字段说明。PS：大多数指标字段无该信息
            ZbaaTarget zbaaTarget = targetService.getTargetByTargetNo(targetNo);
            result.setDefinition(zbaaTarget.getTargetDesc());
            if (zbaaTargetValue!=null && zbaaTargetValue.getCreateTime() != null){
                result.setCreateTime(zbaaTargetValue.getCreateTime());
            }
            result.setTargetGroupOrder(targetGroupOrder);
            result.setTargetValueVO(targetValueVO);
            resultList.add(result);
        }
        return success(resultList);
    }

    /**
     * 保存看板分组订阅信息
     *
     * @param targetGroupVo
     * @return
     */
    @PostMapping("saveTargetGroupOrder")
    @Log(title = "保存看板分组订阅信息", businessType = BusinessType.INSERT)
    @ApiOperation("保存看板分组订阅信息")
    public AjaxResult saveTargetGroupOrder(@RequestBody ZbaaTargetGroupVo targetGroupVo) {
        String groupId = targetGroupVo.getId();
        if (!integralService.checkGroupOrderLimit(groupId)) {
            return error("当前看板分组已达选择指标上限");
        }

        log.info("保存指标看板参数：" + targetGroupVo.toString());
        targetGroupOrderService.saveTargetGroupOrder(targetGroupVo);
        return success();
    }

    /**
     * 修改看板分组订阅信息
     *
     * @param zbaaTargetGroupOrder
     * @return
     */
    @PostMapping("updateTargetGroupOrder")
    @Log(title = "修改看板分组订阅信息")
    @ApiOperation("修改看板分组订阅信息")
    public AjaxResult updateTargetGroupOrder(@RequestBody ZbaaTargetGroupOrder zbaaTargetGroupOrder) {
        Integer result = targetGroupOrderService.update(zbaaTargetGroupOrder);
        return toAjax(result);
    }


    /**
     * 删除看板分组订阅指标信息
     *
     * @param id
     * @return
     */
    @GetMapping("deleteTargetGroupOrder")
    @Log(title = "删除看板分组订阅指标信息")
    @ApiOperation("删除看板分组订阅指标信息")
    public AjaxResult deleteTargetGroupOrder(@RequestParam("id") String id) {
        return toAjax(targetGroupOrderService.delete(id));
    }
}
